<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Role extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //获取所有权限信息
        $roles = model('role')->select();
        return $this->fetch('', ['roles' => $roles]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        if (\request()->isPost()) {
            //接收数据
            $id = input('get.id');
            $data = input('post.');
            $ps_ids = implode(',', $data['role']);
            $ps_cas = 'Index-index';
            //将数据进行组合
            $ps_ca = model('permission')->whereIn('ps_id', $data['role'])->whereIn('ps_level', ['1', '2'])->field("concat(ps_c,'-',ps_a) as a")->select();
            $ps_ca = collection($ps_ca)->toArray();
            foreach ($ps_ca as $v) {
                $ps_cas .= ',' . $v['a'];
            }
            //数据入库
            $res = model('role')->where('role_id', $id)->update(['ps_ids' => $ps_ids, 'ps_ca' => $ps_cas]);
            if ($res) {
                return show('1', '更新成功');
            } else {
                return show('0', '更新失败');
            }
        } else {
            $arr = [];
            $id = input('get.id');
            $role_name = model('role')->get(['role_id' => $id]);
            $permission_A = model('permission')->where('ps_level', '0')->select();
            $permission_B = model('permission')->where('ps_level', '1')->select();
            $permission_C = model('permission')->where('ps_level', '2')->select();
            //前台选中权限
            $ps_ids = model('permission')->whereIn('ps_id', explode(',', $role_name->ps_ids))->select();
            //遍历保存为一维数组
            foreach ($ps_ids as $v) {
                $arr[] = $v->ps_id;
            }
            return $this->fetch('', ['arr' => $arr, 'role' => $role_name, 'permission_A' => $permission_A, 'permission_B' => $permission_B, 'permission_C' => $permission_C]);
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
